import time
import pymysql
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
import threading

# 全局变量用于控制主线程的退出和数据库连接
stop_event = threading.Event()
connections = {}  # 存储连接对象


# 模拟从堡垒机获取不同用户和密码的函数
def get_credentials_from_bastion():
    # 返回一个包含用户名和密码的字典列表
    # 示例格式: [{'user': 'user1', 'password': 'pass1'}, {'user': 'user2', 'password': 'pass2'}]
    return [
        {'user': 'user1', 'password': 'pass1'},
        {'user': 'user2', 'password': 'pass2'}
    ]


# 连接数据库的函数
def connect_to_database(user, password):
    connection = pymysql.connect(
        host='jumpjump.child-healthy.com',
        port=33061,  # 默认 MySQL 端口
        user=user,
        password=password,
        database='',  # 你可以在这里指定数据库名
        charset='utf8',  # 可根据需要修改字符集
        cursorclass=pymysql.cursors.DictCursor
    )
    return connection


# 刷新所有连接
def refresh_all_connections():
    global connections
    credentials = get_credentials_from_bastion()

    for cred in credentials:
        user, password = cred['user'], cred['password']
        if (user, password) not in connections:
            print(f"未找到用户 {user} 的连接，尝试重新连接...")
            connections[(user, password)] = connect_to_database(user, password)

        connection = connections[(user, password)]
        print(f"正在刷新用户 {user} 的数据库连接...")
        try:
            with connection.cursor() as cursor:
                cursor.execute("SELECT 1;")
        except Exception as e:
            print(f"连接刷新失败，尝试重新连接用户 {user}: {e}")
            connection.close()
            del connections[(user, password)]  # 移除失败的连接
            # 重新连接
            connections[(user, password)] = connect_to_database(user, password)


# 主函数，处理数据库操作
def main():
    global connections
    scheduler = BackgroundScheduler()

    # 创建一个调度任务，定期刷新所有连接
    scheduler.add_job(
        refresh_all_connections,
        trigger=IntervalTrigger(minutes=4),  # 每4分钟执行一次
        id='refresh_all_connections_job',
        name='定时刷新所有数据库连接',
        replace_existing=True
    )
    scheduler.start()

    # 启动一个线程来处理用户输入
    def listen_for_stop_signal():
        input("按 Enter 键停止程序...\n")
        stop_event.set()  # 触发停止信号

    input_thread = threading.Thread(target=listen_for_stop_signal)
    input_thread.start()

    try:
        # 让主线程持续运行，直到收到停止信号
        stop_event.wait()  # 等待停止事件

    finally:
        # 完成操作后关闭所有连接
        for conn in connections.values():
            conn.close()
        scheduler.shutdown()  # 关闭调度器
        print("所有数据库连接已关闭。")


if __name__ == "__main__":
    main()

# 刷新多个账号